package utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 李夏
 * @version 1.0
 */
public class CookieUtil {
//实现项目的登录名和密码保存到浏览器一周
        public static void addCookie(String cookieName, int time,
                                     HttpServletRequest request, HttpServletResponse response,
                                     String name, String password, String stuId) {
            //如有该项目保存名字和密码的cookie，则更改cookie的值，如未有则新建cookie
            Cookie cookie=getCookieByName(request,cookieName);
            if(cookie!=null){
                cookie.setValue(name+"#"+password);
            }else{
                cookie=new Cookie(cookieName,name+"#"+password);

            }

            //设置cookie的有效时间
            cookie.setMaxAge(time);
            //设置cookie的作用范围旨在当前项目范围中有效
            cookie.setPath(request.getContextPath());
            System.out.println("request.getContextPath():"+request.getContextPath());

            response.addCookie(cookie);


        }

        public static Cookie getCookieByName(HttpServletRequest request, String cookieName) {
            //从request中获取当前项目的所有cookie
            Cookie[] cookies=request.getCookies();
            //遍历所有cookie
            if(cookies!=null&&cookies.length>0){
                for(Cookie cookie:cookies){
                    if(cookie.getName().equals(cookieName)){
                        return cookie;
                    }
                }
            }
            return null;
        }
    }


